/*
 * Copyright 2002-2005 the original author or authors.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package net.bingosoft.common.swato;

import java.io.IOException;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import net.bingosoft.common.json.JSONObject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Zhijie Chen (zigzag.chen@gmail.com)
 */
public class JSONResponse extends HttpServletResponseWrapper {

	private static Log log = LogFactory.getLog(JSONResponse.class);

	private Object m_result = null;

	private JSONObject m_returnObject = new JSONObject();

	/**
	 * @param resp
	 */
	public JSONResponse(HttpServletResponse resp) {
		super(resp);
		this.setContentType("text/plain;charset=utf-8");
	}

	public void flush() throws IOException {
		String returnString = m_returnObject.toString();
		log.debug("Flush Result: " + returnString);
		this.getWriter().write(returnString);
		this.getWriter().flush();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.swato.json_rpc.JSONResponse#setResult(java.lang.Object)
	 */
	public void setResult(Object result) throws Exception {
		m_result = result;
		m_returnObject.put("result", result);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.swato.json_rpc.JSONResponse#setError(java.lang.Exception)
	 */
	public void setError(Throwable error) {
		m_returnObject.put("error", error.getCause() == null ? error.getLocalizedMessage():error.getCause().getLocalizedMessage());
	}

	public void setHashCode(String hashCode) {
		m_returnObject.put("hashCode", hashCode);
	}

	public Object getResult() {
		return m_result;
	}

	public String getHashCode() {
		return m_returnObject.optString("hashCode");
	}

}
